package cn.changsheng.csfenjie.api;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitScheduler;

import cn.changsheng.csfenjie.main;
import cn.changsheng.csfenjie.config.itemData;
import cn.changsheng.csfenjie.config.setting;
import cn.changsheng.csfenjie.task.ConsStask;
import cn.changsheng.csfenjie.task.OpStask;
import cn.changsheng.csfenjie.utils.ItemSerialize;
import cn.changsheng.csfenjie.utils.Utils;

public class FenJieApi {

	public static ArrayList<ItemStack> startFenJie(ItemStack item, Player p) {
		ArrayList<ItemStack> ItemDataList = new ArrayList<ItemStack>();
		if (Utils.itemDisplayNameIsNull(item) == false) {
			String itemName = Utils.strColorRemove(item.getItemMeta().getDisplayName());
			String chance = setting.get(itemName + ".chance");
			String items = setting.get(itemName + ".item");
			List<String> commandlist = setting.getList(itemName + ".command");
			if (chance != null) {
				double randomNumberInRange = Utils.getRandomNumberInRange(0, 100);
				if (randomNumberInRange > Double.valueOf(chance)) {
					return new ArrayList<ItemStack>();
				}
			}
			if (items != null) {
				if (items.contains(",")) {
					String[] split = items.split(",");
					for (String s : split) {
						String itemData_s = itemData.get(s);
						if (itemData_s != null) {
							ItemDataList.add(new ItemSerialize().toItem(itemData_s));
						}
					}
				}
			}

			// 执行指令
			if (commandlist != null) {
				if (commandlist.size() != 0) {
					for (String cmd : commandlist) {
						String replacecmd = cmd.replace("[OP]", "").replace("[CONSOLE]", "").replace("%player%",
								p.getName());
						if (cmd.contains("[OP]")) {
							BukkitScheduler sched = Bukkit.getServer().getScheduler();
							sched.runTaskLater(main.getInstance(), new OpStask(p, replacecmd), 1L);
						}
						if (cmd.contains("[CONSOLE]")) {
							BukkitScheduler sched = Bukkit.getServer().getScheduler();
							sched.runTaskLater(main.getInstance(), new ConsStask(replacecmd), 1L);
						}
					}
				}
			}

		}
		// 返回分解物
		if (ItemDataList.size() != 0) {
			return ItemDataList;
		}
		return null;
	}
}
